package com.wontube.client.extension.io.protocol;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


import com.wontube.client.extension.io.protocol.php.PHPSerializer;
import com.wontube.client.io.IObjectProtocol;
import com.wontube.client.utils.Base64;


/**
 * @author yuechao
 *
 */
public class PHPObjectProtocol implements IObjectProtocol {
	private final PHPSerializer serializer = new PHPSerializer();

	/* 
	 * @see client.io.IObjectProtocol#toProtoString(java.lang.Object)
	 */
	@Override
	public String toProtoString(Object value) {
		if (value == null) {
			return "";
		}
		
		byte[] buffer = new byte[0];
		try {
			buffer = this.serializer.serialize(value);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		String result = Base64.encode(buffer);
		return result;
	}

	/* 
	 * @see client.io.IObjectProtocol#toObject(java.lang.String, java.lang.reflect.Type)
	 */
	@Override
	public Object toObject(String value, Type type) {
		if (value == null || "".equals(value)) {
			return null;
		}
		
		byte[] buffer = Base64.decode(value);
		try {
			Class<?> clazz = null;
			if (type instanceof Class<?>) {
				clazz = (Class<?>)type;
			} else if (type instanceof ParameterizedType){
				clazz = (Class<?>) ((ParameterizedType)type).getRawType();
			} else {
				clazz = Object.class;
			}
			Object result = this.serializer.unserialize(buffer, clazz);
			return result;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
